package com.health.fragment.person;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import com.health.NovaApplication;
import com.health.PersonalFileActivity;
import com.health.PersonalFileActivity.onFragmentSave;
import com.health.R;
import com.health.adapter.CheckBoxAdapter;
import com.health.db.FDbManager;
import com.health.model.PeopleType;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.ARCHIVE_ENVIRONMENT;
import com.health.tablebean.ARCHIVE_FAMILYHISTORYINFO;
import com.health.tablebean.ARCHIVE_ILLNESSHISTORYINFO;
import com.health.tablebean.BD_DD_INFO;
import com.health.tools.GlobalConts;
import com.health.tools.JBRQData;
import com.health.view.spinner.NiceSpinner;
import com.health.view.spinner.NiceSpinnerAdapter;
import com.health.widget.EditTextWithDate;
import com.health.widget.MyGridView;
import com.nova.BaseFragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 基本信息-健康信息
 *
 * @author Administrator
 */
public class HealthyFragment extends BaseFragment implements OnCheckedChangeListener, OnClickListener, onFragmentSave,
        android.widget.RadioGroup.OnCheckedChangeListener {

    private static final String TAG = "HealthyFragment";
    private static final String ISTAG = "1";
    private View view;
    private ARCHIVE_BASEINFO userInfo;
    private List<BD_DD_INFO> kitchenInfos;
    private List<BD_DD_INFO> fuelInfos;
    private List<BD_DD_INFO> waterInfos;
    private List<BD_DD_INFO> WCInfos;
    private List<BD_DD_INFO> animalInfos;
    private List<EditText> diseaseEts;// 疾病输入框
    private List<CheckBox> diseaseCbs;
    // private List<CheckBox> diseaseCheckedCbs = new ArrayList<CheckBox>();
    private List<BD_DD_INFO> diseasInfos_z;// 总病史
    private List<BD_DD_INFO> diseasInfos_jb;// 疾病史
    private List<BD_DD_INFO> diseasInfos_jzs;// 家族史
    private RadioGroup surgeryRg;
    private RadioGroup traumaRg;
    private RadioGroup transfusureRg;
    private EditText surgeryR1;
    private EditText surgeryR2;
    private EditText traumaR1;
    private EditText traumaR2;
    private EditText transfusurnR1;
    private EditText transfusurnR2;
    private EditTextWithDate[] timeEts;
    private FDbManager fdbmanger = NovaApplication.fdbmanger;
    private RadioButton fatherHistory;
    private RadioButton motherHistory;
    private RadioButton brotherHistory;
    private RadioButton sonHistory;
    private MyGridView fatherGridView;
    private MyGridView motherGridView;
    private MyGridView brotherGridView;
    private MyGridView sonGridView;
    private String strWhere;
    private CheckBoxAdapter fatherAdapter;
    private CheckBoxAdapter motherAdapter;
    private CheckBoxAdapter brotherAdapter;
    private CheckBoxAdapter sonAdapter;
    private List<ARCHIVE_FAMILYHISTORYINFO> historys;
    private NiceSpinner kitchenSp;
    private NiceSpinner fuelSp;
    private NiceSpinner waterSp;
    private NiceSpinner wcSp;
    private NiceSpinner animalSp;
    private NiceSpinnerAdapter<BD_DD_INFO> kitchenAdapter;
    private NiceSpinnerAdapter<BD_DD_INFO> fuelAdapter;
    private NiceSpinnerAdapter<BD_DD_INFO> waterAdapter;
    private NiceSpinnerAdapter<BD_DD_INFO> animalAdapter;
    private NiceSpinnerAdapter<BD_DD_INFO> wcAdaper;
    private List<ARCHIVE_ENVIRONMENT> environmentList;
    private String strOrder;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
    private boolean checkAlertFlag;
    private List<ARCHIVE_ILLNESSHISTORYINFO> oldList;
    private ScrollView scrollView;
    /**
     * 是否精神病
     */
    private boolean isPsychosis;
    /**
     * 是否高血压
     */
    private boolean isHypertension;//
    /**
     * 是否糖尿病
     */
    private boolean isDiabetes;//
    /**
     * 是否冠心病
     */
    private boolean isCHD;//
    /**
     * 是否脑卒中
     */
    private boolean isStroke;
    // /** 是否残疾人 */
    // private boolean isHandicapped;
    /**
     * 是否肺结核
     */
    private boolean isTB;
    CheckBox dieaseNo;
    CheckBox gaoxueyaCb;
    CheckBox tangniaobingCb;
    CheckBox guanxinbingCb;
    CheckBox feibingCb;
    CheckBox zhongliuCb;
    CheckBox naocuzhongCb;
    CheckBox jingshenbingCb;
    CheckBox jiehebingCb;
    CheckBox ganyanCb;
    CheckBox qtfdcrbCb;
    CheckBox zhiyebingCb;
    CheckBox ohterCb;
    EditTextWithDate timeEt1;
    EditTextWithDate timeEt2;
    EditTextWithDate timeEt3;
    EditTextWithDate timeEt4;
    EditTextWithDate timeEt5;
    EditTextWithDate timeEt6;

    EditTextWithDate rTimeEt1;
    EditTextWithDate rTimeEt2;
    EditTextWithDate rTimeEt3;
    EditTextWithDate rTimeEt4;
    EditTextWithDate rTimeEt5;
    EditTextWithDate rTimeEt6;

    EditText disease1Et;
    EditText disease2Et;
    EditText disease3Et;
    EditText disease4Et;
    EditText disease5Et;
    EditText disease6Et;
    private RadioButton surgeryyes_rb;
    private RadioButton traumayes_rb;
    private RadioButton transfusurnyes_rb;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.healthy, container, false);
        userInfo = NovaApplication.getUserInfo();
        getGroup();
        strWhere = "IDCARD LIKE  '" + userInfo.getIDCARD() + "'";
        strOrder = "CAST(SORT AS int ASC)";
        checkAlertFlag = false;
        initView();
        setData();
        checkAlertFlag = true;
        return view;
    }

    @Override
    public void onStart() {

        super.onStart();
        // userInfo = NovaApplication.getUserInfo();
        // getGroup();
        // strWhere = "IDCARD LIKE '" + userInfo.getIDCARD() + "'";
        // strOrder = "CAST(SORT AS int ASC)";
        // checkAlertFlag = false;
        // initView();
        // setData();
        // checkAlertFlag = true;
    }

    private void initView() {
        scrollView = (ScrollView) view.findViewById(R.id.healthy_scrollView);
        fatherGridView = (MyGridView) view.findViewById(R.id.healthy_familyhistory_father);
        motherGridView = (MyGridView) view.findViewById(R.id.healthy_familyhistory_mother);
        brotherGridView = (MyGridView) view.findViewById(R.id.healthy_familyhistory_brother);
        sonGridView = (MyGridView) view.findViewById(R.id.healthy_familyhistory_son);

        diseasInfos_z = fdbmanger.findAllByWhereInInfoDB(BD_DD_INFO.class, "PARENTID LIKE 'DM99-01'", strOrder);
        int size = diseasInfos_z.size();
        diseasInfos_jb = new ArrayList<BD_DD_INFO>();
        diseasInfos_jzs = new ArrayList<BD_DD_INFO>();
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                String str_id = diseasInfos_z.get(i).getID();
                // DM99-01_99 其他； DM99-01_98 其他法定传染病 ； DM99-01_9 结核病； DM99-01_8
                // 严重精神障碍；
                // DM99-01_7 脑卒中； DM99-01_6 恶性肿瘤；DM99-01_5 慢性阻塞性肺疾病
                // DM99-01_4 冠心病； DM99-01_3 糖尿病；DM99-01_2 高血压； DM99-01_15 哮喘
                // DM99-01_14 贫血； DM99-01_13 肾脏疾病； DM99-01_12 职业病
                // DM99-01_11 先天畸形； DM99-01_10 肝炎； DM99-01_1 无
                if (str_id.equals("DM99-01_1") || str_id.equals("DM99-01_2") || str_id.equals("DM99-01_3")
                        || str_id.equals("DM99-01_4") || str_id.equals("DM99-01_5") || str_id.equals("DM99-01_6")
                        || str_id.equals("DM99-01_7") || str_id.equals("DM99-01_8") || str_id.equals("DM99-01_9")
                        || str_id.equals("DM99-01_10")) {
                    diseasInfos_jb.add(diseasInfos_z.get(i));
                    diseasInfos_jzs.add(diseasInfos_z.get(i));
                }
                if (str_id.equals("DM99-01_12") || str_id.equals("DM99-01_98") || str_id.equals("DM99-01_99")) {
                    diseasInfos_jb.add(diseasInfos_z.get(i));
                }
                if (str_id.equals("DM99-01_11") || str_id.equals("DM99-01_99")) {
                    diseasInfos_jzs.add(diseasInfos_z.get(i));
                }
            }
        }

        // List<BD_DD_INFO> subList = diseasInfos.subList(0, 10);
        // subList.add(diseasInfos.get(diseasInfos.size() - 1));
        fatherAdapter = new CheckBoxAdapter(getActivity(), diseasInfos_jzs);
        fatherAdapter.setOtherMaxLength(50);
        fatherGridView.setAdapter(fatherAdapter);
        // fatherAdapter.setOtherVis(false);

        motherAdapter = new CheckBoxAdapter(getActivity(), diseasInfos_jzs);
        motherAdapter.setOtherMaxLength(50);
        motherGridView.setAdapter(motherAdapter);
        // motherAdapter.setOtherVis(false);
        brotherAdapter = new CheckBoxAdapter(getActivity(), diseasInfos_jzs);
        brotherAdapter.setOtherMaxLength(50);
        brotherGridView.setAdapter(brotherAdapter);
        // brotherAdapter.setOtherVis(false);

        sonAdapter = new CheckBoxAdapter(getActivity(), diseasInfos_jzs);
        sonGridView.setAdapter(sonAdapter);
        // sonAdapter.setOtherVis(false);

        surgeryRg = (RadioGroup) view.findViewById(R.id.healthy_surgery_rg);
        surgeryyes_rb = (RadioButton) view.findViewById(R.id.healthy_surgeryyes_rb);
        traumayes_rb = (RadioButton) view.findViewById(R.id.healthy_traumayes_rb);
        transfusurnyes_rb = (RadioButton) view.findViewById(R.id.healthy_transfusurnyes_rb);
        traumaRg = (RadioGroup) view.findViewById(R.id.healthy_trauma_rg);
        transfusureRg = (RadioGroup) view.findViewById(R.id.healthy_transfusurn_rg);

        surgeryR1 = (EditText) view.findViewById(R.id.healthy_surgery_reason1_et);
        surgeryR2 = (EditText) view.findViewById(R.id.healthy_surgery_reason2_et);
        traumaR1 = (EditText) view.findViewById(R.id.healthy_trauma_reason1_et);
        traumaR2 = (EditText) view.findViewById(R.id.healthy_trauma_reason2_et);
        transfusurnR1 = (EditText) view.findViewById(R.id.healthy_transfusurn_reason1_et);
        transfusurnR2 = (EditText) view.findViewById(R.id.healthy_transfusurn_reason2_et);

        // diseaseNames = new String[]
        // {"DM99-01_1","DM99-01_2","","","","","","","","","","","","","","",""};

        disease1Et = (EditText) view.findViewById(R.id.healthy_disease1);
        disease2Et = (EditText) view.findViewById(R.id.healthy_disease2);
        disease3Et = (EditText) view.findViewById(R.id.healthy_disease3);
        disease4Et = (EditText) view.findViewById(R.id.healthy_disease4);
        disease5Et = (EditText) view.findViewById(R.id.healthy_disease5);
        disease6Et = (EditText) view.findViewById(R.id.healthy_disease6);

        rTimeEt1 = (EditTextWithDate) view.findViewById(R.id.healthy_surgery_time1_et);
        rTimeEt2 = (EditTextWithDate) view.findViewById(R.id.healthy_surgery_time2_et);
        rTimeEt3 = (EditTextWithDate) view.findViewById(R.id.healthy_trauma_time1_et);
        rTimeEt4 = (EditTextWithDate) view.findViewById(R.id.healthy_trauma_time2_et);
        rTimeEt5 = (EditTextWithDate) view.findViewById(R.id.healthy_transfusurn_time1_et);
        rTimeEt6 = (EditTextWithDate) view.findViewById(R.id.healthy_transfusurn_time2_et);

        timeEt1 = (EditTextWithDate) view.findViewById(R.id.healthy_time1);
        timeEt2 = (EditTextWithDate) view.findViewById(R.id.healthy_time2);
        timeEt3 = (EditTextWithDate) view.findViewById(R.id.healthy_time3);
        timeEt4 = (EditTextWithDate) view.findViewById(R.id.healthy_time4);
        timeEt5 = (EditTextWithDate) view.findViewById(R.id.healthy_time5);
        timeEt6 = (EditTextWithDate) view.findViewById(R.id.healthy_time6);

        timeEts = new EditTextWithDate[]{rTimeEt1, rTimeEt2, rTimeEt3, rTimeEt4, rTimeEt5, rTimeEt6, timeEt1, timeEt2,
                timeEt3, timeEt4, timeEt5, timeEt6};

        int length = timeEts.length;
        for (int i = 0; i < length; i++) {
            timeEts[i].setBefore(new Date());
        }

        diseaseEts = new ArrayList<EditText>();
        diseaseEts.add(disease1Et);
        diseaseEts.add(disease2Et);
        diseaseEts.add(disease3Et);
        diseaseEts.add(disease4Et);
        diseaseEts.add(disease5Et);
        diseaseEts.add(disease6Et);

        dieaseNo = (CheckBox) view.findViewById(R.id.healthy_disease_no_cb);
        gaoxueyaCb = (CheckBox) view.findViewById(R.id.healthy_disease_gaoxueya_cb);
        tangniaobingCb = (CheckBox) view.findViewById(R.id.healthy_disease_tangniaobing_cb);
        guanxinbingCb = (CheckBox) view.findViewById(R.id.healthy_disease_guanxinbing_cb);
        feibingCb = (CheckBox) view.findViewById(R.id.healthy_disease_feibing_cb);
        zhongliuCb = (CheckBox) view.findViewById(R.id.healthy_disease_zhongliu_cb);
        naocuzhongCb = (CheckBox) view.findViewById(R.id.healthy_disease_naocuizhong_cb);
        jingshenbingCb = (CheckBox) view.findViewById(R.id.healthy_disease_jinshenbing_cb);
        jiehebingCb = (CheckBox) view.findViewById(R.id.healthy_disease_jiehe_cb);
        ganyanCb = (CheckBox) view.findViewById(R.id.healthy_disease_ganyan_cb);
        qtfdcrbCb = (CheckBox) view.findViewById(R.id.healthy_disease_qtfdcrb_cb);
        zhiyebingCb = (CheckBox) view.findViewById(R.id.healthy_disease_zhiyebing_cb);
        ohterCb = (CheckBox) view.findViewById(R.id.healthy_disease_other_cb);
        diseaseCbs = new ArrayList<CheckBox>();
        diseaseCbs.add(dieaseNo);
        diseaseCbs.add(gaoxueyaCb);
        diseaseCbs.add(tangniaobingCb);
        diseaseCbs.add(guanxinbingCb);
        diseaseCbs.add(feibingCb);
        diseaseCbs.add(zhongliuCb);
        diseaseCbs.add(naocuzhongCb);
        diseaseCbs.add(jingshenbingCb);
        diseaseCbs.add(jiehebingCb);
        diseaseCbs.add(ganyanCb);
        diseaseCbs.add(qtfdcrbCb);
        diseaseCbs.add(zhiyebingCb);
        diseaseCbs.add(ohterCb);

        dieaseNo.setOnCheckedChangeListener(this);
        gaoxueyaCb.setOnCheckedChangeListener(this);
        tangniaobingCb.setOnCheckedChangeListener(this);
        guanxinbingCb.setOnCheckedChangeListener(this);
        feibingCb.setOnCheckedChangeListener(this);
        zhongliuCb.setOnCheckedChangeListener(this);
        naocuzhongCb.setOnCheckedChangeListener(this);
        jingshenbingCb.setOnCheckedChangeListener(this);
        jiehebingCb.setOnCheckedChangeListener(this);
        ganyanCb.setOnCheckedChangeListener(this);
        qtfdcrbCb.setOnCheckedChangeListener(this);
        zhiyebingCb.setOnCheckedChangeListener(this);
        ohterCb.setOnCheckedChangeListener(this);

        kitchenSp = (NiceSpinner) view.findViewById(R.id.healthy_kitchen_sp);
        fuelSp = (NiceSpinner) view.findViewById(R.id.healthy_fuel_sp);
        waterSp = (NiceSpinner) view.findViewById(R.id.healthy_water_sp);
        wcSp = (NiceSpinner) view.findViewById(R.id.healthy_wc_sp);
        animalSp = (NiceSpinner) view.findViewById(R.id.healthy_animal_sp);
        OnClickListener spClick = new OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        };
        kitchenSp.setOnClickListener(spClick);
        fuelSp.setOnClickListener(spClick);
        waterSp.setOnClickListener(spClick);
        wcSp.setOnClickListener(spClick);
        animalSp.setOnClickListener(spClick);

        kitchenInfos = fdbmanger.findAllByWhereInInfoDB(BD_DD_INFO.class, "PARENTID LIKE 'DM01-16'",
                "CAST(SORT AS int ASC)");
        // FROM [BD_DD_INFO] WHERE PARENTID LIKE 'DM02-05' ORDER BY CAST(SORT AS
        // int ASC)
        fuelInfos = fdbmanger.findAllByWhereInInfoDB(BD_DD_INFO.class, "PARENTID LIKE 'DM02-05'",
                "CAST(SORT AS int ASC)");

        waterInfos = fdbmanger.findAllByWhereInInfoDB(BD_DD_INFO.class, "PARENTID LIKE 'DM02-04'",
                "CAST(SORT AS int ASC)");
        WCInfos = fdbmanger.findAllByWhereInInfoDB(BD_DD_INFO.class, "PARENTID LIKE 'DM02-03'",
                "CAST(SORT AS int ASC)");
        animalInfos = fdbmanger.findAllByWhereInInfoDB(BD_DD_INFO.class, "PARENTID LIKE 'DM01-17'",
                "CAST(SORT AS int ASC)");

        fatherHistory = (RadioButton) view.findViewById(R.id.healthy_father_btn);
        // fatherHistory.setChecked(true);
        motherHistory = (RadioButton) view.findViewById(R.id.healthy_mother_btn);
        brotherHistory = (RadioButton) view.findViewById(R.id.healthy_brother_btn);
        sonHistory = (RadioButton) view.findViewById(R.id.healthy_son_btn);
        fatherHistory.setOnCheckedChangeListener(this);
        motherHistory.setOnCheckedChangeListener(this);
        brotherHistory.setOnCheckedChangeListener(this);
        sonHistory.setOnCheckedChangeListener(this);

        GlobalConts.setMaxLength(50, surgeryR1);// 手术原因1
        GlobalConts.setMaxLength(50, surgeryR2);// 手术原因2
        GlobalConts.setMaxLength(50, traumaR1);// 外伤原因1
        GlobalConts.setMaxLength(50, traumaR1); // 外伤原因2
        GlobalConts.setMaxLength(50, transfusurnR1); // 输血原因1
        GlobalConts.setMaxLength(50, transfusurnR1); // 输血原因2

        // GlobalConts.setMaxLength(50, editTexts); // 疾病其他
        // GlobalConts.setMaxLength(50, editTexts); // 疾病1
        // GlobalConts.setMaxLength(50, editTexts); // 疾病2
        // GlobalConts.setMaxLength(50, editTexts); // 疾病3
        // GlobalConts.setMaxLength(50, editTexts); // 疾病4
        // GlobalConts.setMaxLength(50, editTexts); // 疾病5
        // GlobalConts.setMaxLength(50, editTexts); // 疾病6
        //
        // GlobalConts.setMaxLength(length, editTexts);// 家族史其他
        // 设置手术、输血、外伤
        onCheckedChanged(surgeryRg, -1);
        onCheckedChanged(traumaRg, -1);
        onCheckedChanged(transfusureRg, -1);

        transfusureRg.check(R.id.healthy_transfusurnno_rb);
        traumaRg.check(R.id.healthy_traumano_rb);
        surgeryRg.check(R.id.healthy_surgeryno_rb);
        addlistener();
    }

    private void addlistener() {
        disease1Et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    timeEt1.setDate(new Date());
                } else {
                    timeEt1.setText("");
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        disease2Et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    timeEt2.setDate(new Date());
                } else {
                    timeEt2.setText("");
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        disease3Et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    timeEt3.setDate(new Date());
                } else {
                    timeEt3.setText("");
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        disease4Et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    timeEt4.setDate(new Date());
                } else {
                    timeEt4.setText("");
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        disease5Et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    timeEt5.setDate(new Date());
                } else {
                    timeEt5.setText("");
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        disease6Et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    timeEt6.setDate(new Date());
                } else {
                    timeEt6.setText("");
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    private void setData() {
        List<ARCHIVE_ILLNESSHISTORYINFO> surgerInfos = fdbmanger.findAllByWhere(ARCHIVE_ILLNESSHISTORYINFO.class,
                strWhere, "ID");

        if (surgerInfos.size() > 0) {
            for (ARCHIVE_ILLNESSHISTORYINFO info : surgerInfos) {
                // 1:疾病,2:手术,3:外伤,4:输血
                if (info.getILLNESSTYPE().equals("2")) {
                    // 2:手术
                    surgeryRg.check(R.id.healthy_surgeryyes_rb);
                    if (TextUtils.isEmpty(surgeryR1.getText().toString())
                            && !TextUtils.isEmpty(info.getILLNESSNAME_OTHER())) {
                        surgeryR1.setText(info.getILLNESSNAME_OTHER());
                        if (info.getDIAGNOSETIME() != null)
                            timeEts[0].setText(format.format(info.getDIAGNOSETIME()));
                    } else {
                        surgeryR2.setText(info.getILLNESSNAME_OTHER());
                        if (info.getDIAGNOSETIME() != null)
                            timeEts[1].setText(format.format(info.getDIAGNOSETIME()));
                    }
                } else if (info.getILLNESSTYPE().equals("3")) {
                    // 3:外伤
                    traumaRg.check(R.id.healthy_traumayes_rb);
                    if (TextUtils.isEmpty(traumaR1.getText().toString())
                            && !TextUtils.isEmpty(info.getILLNESSNAME_OTHER())) {
                        traumaR1.setText(info.getILLNESSNAME_OTHER());
                        if (info.getDIAGNOSETIME() != null)
                            timeEts[2].setText(format.format(info.getDIAGNOSETIME()));
                    } else {
                        traumaR2.setText(info.getILLNESSNAME_OTHER());
                        if (info.getDIAGNOSETIME() != null)
                            timeEts[3].setText(format.format(info.getDIAGNOSETIME()));
                    }
                } else if (info.getILLNESSTYPE().equals("4")) {// &&
                    // !TextUtils.isEmpty(info.getILLNESSNAME_OTHER())
                    // 4:输血
                    transfusureRg.check(R.id.healthy_transfusurnyes_rb);
                    if (TextUtils.isEmpty(transfusurnR1.getText().toString())) {
                        transfusurnR1.setText(info.getILLNESSNAME_OTHER());
                        if (info.getDIAGNOSETIME() != null)
                            timeEts[4].setText(format.format(info.getDIAGNOSETIME()));
                    } else {
                        transfusurnR2.setText(info.getILLNESSNAME_OTHER());
                        if (info.getDIAGNOSETIME() != null)
                            timeEts[5].setText(format.format(info.getDIAGNOSETIME()));
                    }
                }

            }
        }

        ;


        checkIsChecked(surgeryyes_rb, surgeryR1, rTimeEt1, surgeryR2, rTimeEt2);
        checkIsChecked(traumayes_rb, traumaR1, rTimeEt3, traumaR2, rTimeEt4);
        checkIsChecked(transfusurnyes_rb, transfusurnR1, rTimeEt5, transfusurnR2, rTimeEt6);

        setJWS();

        surgeryRg.setOnCheckedChangeListener(this);
        traumaRg.setOnCheckedChangeListener(this);
        transfusureRg.setOnCheckedChangeListener(this);

        // 家族史
        historys = fdbmanger.findAllByWhere(ARCHIVE_FAMILYHISTORYINFO.class, strWhere);
        if (historys.size() > 0) {
            ARCHIVE_FAMILYHISTORYINFO history = historys.get(0);
            String fatherHis = history.getFATHERHISTORY();
            String motherHis = history.getMOTHERHISTORY();
            String brotherHis = history.getBROTHERSISTERHISTORY();
            String sonHis = history.getCHILDRENHISTORY();
            if (!TextUtils.isEmpty(fatherHis)) {
                fatherHistory.setChecked(true);
            } else if (TextUtils.isEmpty(fatherHis) && !TextUtils.isEmpty(motherHis)) {
                motherHistory.setChecked(true);
            } else if (TextUtils.isEmpty(fatherHis) && TextUtils.isEmpty(motherHis) && !TextUtils.isEmpty(brotherHis)) {
                brotherHistory.setChecked(true);
            } else if (TextUtils.isEmpty(fatherHis) && TextUtils.isEmpty(motherHis) && TextUtils.isEmpty(brotherHis)
                    && !TextUtils.isEmpty(sonHis)) {
                sonHistory.setChecked(true);
            }

            if (!TextUtils.isEmpty(fatherHis)) {
                fatherAdapter.setCheckedCodeList(Arrays.asList(fatherHis.split(",")));
            }
            fatherAdapter.setOther(
                    TextUtils.isEmpty(history.getFATHERHISTORY_OTHER()) ? "" : history.getFATHERHISTORY_OTHER());
            if (!TextUtils.isEmpty(motherHis)) {
                motherAdapter.setCheckedCodeList(Arrays.asList(motherHis.split(",")));
            }
            motherAdapter.setOther(
                    TextUtils.isEmpty(history.getMOTHERHISTORY_OTHER()) ? "" : history.getMOTHERHISTORY_OTHER());
            if (!TextUtils.isEmpty(brotherHis)) {
                brotherAdapter.setCheckedCodeList(Arrays.asList(brotherHis.split(",")));
            }
            brotherAdapter.setOther(TextUtils.isEmpty(history.getBROTHERSISTERHISTORY_OTHER()) ? ""
                    : history.getBROTHERSISTERHISTORY_OTHER());
            if (!TextUtils.isEmpty(sonHis)) {
                sonAdapter.setCheckedCodeList(Arrays.asList(sonHis.split(",")));
            }
            sonAdapter.setOther(
                    TextUtils.isEmpty(history.getCHILDRENHISTORY_OTHER()) ? "" : history.getCHILDRENHISTORY_OTHER());
        }

        kitchenAdapter = new NiceSpinnerAdapter<BD_DD_INFO>(getActivity(), kitchenInfos);
        fuelAdapter = new NiceSpinnerAdapter<BD_DD_INFO>(getActivity(), fuelInfos);
        waterAdapter = new NiceSpinnerAdapter<BD_DD_INFO>(getActivity(), waterInfos);
        animalAdapter = new NiceSpinnerAdapter<BD_DD_INFO>(getActivity(), animalInfos);
        wcAdaper = new NiceSpinnerAdapter<BD_DD_INFO>(getActivity(), WCInfos);

        // kitchenSp.setAdapter(kitchenAdapter);
        // fuelSp.setAdapter(fuelAdapter);
        // waterSp.setAdapter(waterAdapter);
        // animalSp.setAdapter(animalAdapter);
        // wcSp.setAdapter(wcAdaper);
        kitchenSp.attachDataSource(kitchenInfos);
        fuelSp.attachDataSource(fuelInfos);
        waterSp.attachDataSource(waterInfos);
        animalSp.attachDataSource(animalInfos);
        wcSp.attachDataSource(WCInfos);
        // 环境
        environmentList = NovaApplication.fdbmanger.findAllByWhere(ARCHIVE_ENVIRONMENT.class, strWhere);
        if (environmentList.size() > 0) {
            ARCHIVE_ENVIRONMENT envir = environmentList.get(0);
            if (envir != null) {
                kitchenSp.setSelectedIndex(getEnvironment(envir.getBLOWMEASURE(), kitchenInfos));
                fuelSp.setSelectedIndex(getEnvironment(envir.getFUELTYPE(), fuelInfos));
                waterSp.setSelectedIndex(getEnvironment(envir.getDRINKWATER(), waterInfos));
                animalSp.setSelectedIndex(getEnvironment(envir.getLIVESTOCKRAIL(), animalInfos));
                wcSp.setSelectedIndex(getEnvironment(envir.getTOILET(), WCInfos));
            }
        }

    }

    private void checkIsChecked(RadioButton rb, TextView tv1, EditTextWithDate ed1, TextView tv2,
                                EditTextWithDate ed2) {
        if (rb.isChecked()) {
            tv1.setEnabled(true);
            tv2.setEnabled(true);
            ed1.setDatePickerEnabled(true);
            ed2.setDatePickerEnabled(true);
        }

    }

    /**
     * 设置既往史疾病
     */

    private void setJWS() {
        List<ARCHIVE_ILLNESSHISTORYINFO> jbs = fdbmanger.findAllByWhere(ARCHIVE_ILLNESSHISTORYINFO.class,
                strWhere + " and ILLNESSTYPE='1'", "ID");

        int size = jbs.size();
        if (size > 0 && size < 7) {

            for (int i = 0; i < size; i++) {
                ARCHIVE_ILLNESSHISTORYINFO jb = jbs.get(i);
                String text = getDiseasName(jb.getILLNESSNAME());
                Log.e("========", text + "-----" + jb.toString());
                if (!TextUtils.isEmpty(text)) {
                    // 设置复选框
                    for (int j = 0; j < diseaseCbs.size(); j++) {
                        if (text.equals(diseaseCbs.get(j).getText().toString())) {
                            diseaseCbs.get(j).setChecked(true);
                        }
                    }
                }
                if ("无".equals(text)) {
                    return;
                }
                if (text.equals("恶性肿瘤")) {
                    text = "恶性肿瘤" + "(" + jb.getTHERIOMA() + ")";
                } else if (text.equals("职业病")) {
                    text = "职业病" + "(" + jb.getJOBILLNESS() + ")";
                } else if (text.equals("其他")) {
                    text = "其他" + "(" + jb.getILLNESS_OTHER() + ")";
                }
                diseaseEts.get(i).setText(text);
                String time;
                if (jbs.get(i).getDIAGNOSETIME() != null) {
                    time = format.format(jb.getDIAGNOSETIME());
                } else {
                    time = "";
                }
                timeEts[i + 6].setText(time);
            }
        }

    }

    private int getEnvironment(String envirCode, List<BD_DD_INFO> list) {
        for (int i = 0; i < list.size(); i++) {
            if (envirCode != null) {
                if (envirCode.equals(list.get(i).getID())) {
                    return i;
                }
            }
        }

        return 0;

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // 设置疾病
        if (!setCheckMax()) {
            // 已经大于6个
            for (int i = 0; i < diseaseCbs.size(); i++) {
                if (diseaseCbs.get(i).isChecked()) {
                    // 选中的可以在操作
                } else {
                    // 未选中的不可以在操作
                    diseaseCbs.get(i).setEnabled(false);
                }
            }
        } else {
            for (int i = 0; i < diseaseCbs.size(); i++) {
                diseaseCbs.get(i).setEnabled(true);
            }
        }

        if (isChecked) {
            // 疾病
            getGroup();
            int indexOf = diseaseCbs.indexOf(buttonView);

            if (indexOf != -1 && indexOf != 0) {
                // 设置其他疾病
                onCheckJBLX(buttonView, indexOf);

            } else if (indexOf == 0) {
                // 无，设置其他疾病不被选中
                for (int i = 1; i < diseaseCbs.size(); i++) {
                    CheckBox cb = diseaseCbs.get(i);
                    cb.setChecked(false);
                    cb.setEnabled(false);
                }
                clearGroup(null);
            } else {
                int id = buttonView.getId();
                // 家族史
                if (id == R.id.healthy_father_btn) {
                    fatherAdapter.setOtherVis(true);
                    setRadioVisible(fatherGridView);
                } else if (id == R.id.healthy_mother_btn) {
                    motherAdapter.setOtherVis(true);
                    setRadioVisible(motherGridView);
                } else if (id == R.id.healthy_brother_btn) {
                    brotherAdapter.setOtherVis(true);
                    setRadioVisible(brotherGridView);
                } else if (id == R.id.healthy_son_btn) {
                    setRadioVisible(sonGridView);
                    sonAdapter.setOtherVis(true);
                } else {
                }
            }

        } else {
            // 没有被选中
            int id = buttonView.getId();
            if (id == R.id.healthy_disease_no_cb) {
                for (CheckBox cb : diseaseCbs) {
                    cb.setEnabled(true);
                }
            } else {
            }
            for (EditText et : diseaseEts) {
                String ill = et.getText().toString();
                String text = buttonView.getText().toString();
                if (ill.contains(text)) {
                    et.setText("");
                }

            }

        }

    }

    /**
     * 设置疾病类型
     *
     * @param buttonView
     * @param indexOf
     * @author 王婷婷
     * @date 2017年9月22日 上午10:57:13
     */
    private void onCheckJBLX(CompoundButton buttonView, int indexOf) {
        // showButtonDialog("是否将人员列入"+diseasInfos.get(indexOf).getDATAINFO()+"人员");
        for (EditText et : diseaseEts) {
            if (TextUtils.isEmpty(et.getText().toString())) {
                String illText = buttonView.getText().toString();
                if (illText.equals("恶性肿瘤")) {
                    List<ARCHIVE_ILLNESSHISTORYINFO> illList = fdbmanger
                            .findAllByWhere(ARCHIVE_ILLNESSHISTORYINFO.class, strWhere, "ID");
                    ARCHIVE_ILLNESSHISTORYINFO info = getInfo(illList, "DM99-01_6");
                    if (info != null) {
                        et.setText("恶性肿瘤" + "(" + info.getTHERIOMA() + ")");
                    }
                    break;
                } else if (illText.equals("职业病")) {
                    List<ARCHIVE_ILLNESSHISTORYINFO> illList = fdbmanger
                            .findAllByWhere(ARCHIVE_ILLNESSHISTORYINFO.class, strWhere, "ID");
                    ARCHIVE_ILLNESSHISTORYINFO info = getInfo(illList, "DM99-01_12");
                    if (info != null) {
                        et.setText("职业病" + "(" + info.getJOBILLNESS() + ")");
                    }
                    break;
                } else if (illText.equals("其他")) {
                    List<ARCHIVE_ILLNESSHISTORYINFO> illList = fdbmanger
                            .findAllByWhere(ARCHIVE_ILLNESSHISTORYINFO.class, strWhere, "ID");
                    ARCHIVE_ILLNESSHISTORYINFO info = getInfo(illList, "DM99-01_99");
                    if (info != null) {
                        et.setText("其他" + "(" + info.getILLNESS_OTHER() + ")");
                    }
                    break;
                }
                et.setText(illText);

                break;
            }
        }
        if (indexOf == 1) {
            // 高血压
            if (!isHypertension) {
                // saveJBLX(PeopleType.GXY);
//				showConfirmAlert(indexOf);
            }
        } else if (indexOf == 2) {
            // 糖尿病
            if (!isDiabetes) {
                // saveJBLX(PeopleType.TNB);
//				showConfirmAlert(indexOf);
            }
        } else if (indexOf == 3) {
            // 冠心病
            if (!isCHD) {
//				showConfirmAlert(indexOf);
            }
        } else if (indexOf == 5) {
            showTextAlert("恶性肿瘤");
        } else if (indexOf == 6) {
            // 脑卒中
            if (!isStroke) {
//				showConfirmAlert(indexOf);
            }
        } else if (indexOf == 7) {
            // 严重精神障碍
            if (!isPsychosis) {
//				showConfirmAlert(indexOf);
            }
        } else if (indexOf == 8) {
            // 结核病
            if (!isTB) {
//				showConfirmAlert(indexOf);
            }
        } else if (indexOf == 11) {
            showTextAlert("职业病");
        } else if (indexOf == 12) {
            showTextAlert("其他");
        } else {
        }
    }

    private void showTextAlert(final String name) {
        if (!checkAlertFlag) {
            return;
        }
        final EditText et = new EditText(getActivity());
        GlobalConts.setMaxLength(50, et);
        new AlertDialog.Builder(getActivity()).setTitle("请输入疾病名称").setIcon(android.R.drawable.ic_dialog_info)
                .setView(et).setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                String text = et.getText().toString();

                if (name.equals("恶性肿瘤")) {
                    setDieaseText("恶性肿瘤" + "(" + text + ")", name);

                } else if (name.equals("职业病")) {
                    setDieaseText("职业病" + "(" + text + ")", name);
                } else if (name.equals("其他")) {
                    setDieaseText("其他" + "(" + text + ")", name);
                }

            }

            private void setDieaseText(String text, String ill) {
                for (EditText et : diseaseEts) {
                    if (et.getText().toString().contains(ill) || TextUtils.isEmpty(et.getText().toString())) {
                        et.setText(text);
                        break;
                    }
                }
            }
        }).setNegativeButton("取消", null).show();

    }

    private void showConfirmAlert(final int indexOf) {
        if (checkAlertFlag) {
            Dialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("人群划分")
                    .setMessage("是否将人员列入" + diseasInfos_jb.get(indexOf).getDATAINFO() + "人员")
                    .setIcon(R.drawable.ic_launcher).setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // switch (indexOf) {
                            // case 1:
                            // saveIll("6");
                            // break;
                            // case 2:
                            // saveIll("7");
                            // break;
                            // case 3:
                            // saveIll("8");
                            // break;
                            // case 6:
                            // saveIll("9");
                            // break;
                            // case 7:
                            // saveIll("5");
                            // break;
                            // case 8:
                            // saveIll("11");
                            // break;
                            // default:
                            // break;
                            // }
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).create();
            alertDialog.show();
        }
    }

    private void saveIll(String index) {
        String popType = userInfo.getPOPULATION_TYPE();
        if (TextUtils.isEmpty(popType)) {
            popType = index;
        } else {
            String pop = "";
            String[] split = popType.split(",");
            for (String str : split) {
                if (!str.equals("1")) {
                    pop += str + ",";
                }

            }
            popType = pop + index;

        }
        userInfo.setPOPULATION_TYPE(popType);
        NovaApplication.setUserInfo(userInfo);
        fdbmanger.updata(userInfo);
        PersonalFileActivity activity = (PersonalFileActivity) getActivity();
        activity.freshDetailInfoData();
    }

    private void saveOrDelete(List<ARCHIVE_ILLNESSHISTORYINFO> xinList, List<ARCHIVE_ILLNESSHISTORYINFO> oldList) {
        List<ARCHIVE_ILLNESSHISTORYINFO> saveList = new ArrayList<ARCHIVE_ILLNESSHISTORYINFO>();
        for (ARCHIVE_ILLNESSHISTORYINFO xinInfo : xinList) {

            if (oldList.contains(xinInfo)) {
                saveList.add(xinInfo);
            } else {
                xinInfo.setNGUID(UUID.randomUUID().toString());
                saveList.add(xinInfo);
            }

        }
        for (ARCHIVE_ILLNESSHISTORYINFO dInfo : oldList) {

            fdbmanger.delete(dInfo);
        }

        for (ARCHIVE_ILLNESSHISTORYINFO saveInfo : saveList) {
            fdbmanger.save(saveInfo);
        }

    }

    /**
     * 保存数据
     */
    public void save() {

        if (!dieaseNo.isChecked() &&
                !gaoxueyaCb.isChecked() &&
                !tangniaobingCb.isChecked() &&
                !guanxinbingCb.isChecked() &&
                !feibingCb.isChecked() &&
                !zhongliuCb.isChecked() &&
                !naocuzhongCb.isChecked() &&
                !jingshenbingCb.isChecked() &&
                !jiehebingCb.isChecked() &&
                !ganyanCb.isChecked() &&
                !qtfdcrbCb.isChecked() &&
                !zhiyebingCb.isChecked() &&
                !ohterCb.isChecked()) {
            showTextDialog("请选择疾病！");
            return;
        }
        oldList = fdbmanger.findAllByWhere(ARCHIVE_ILLNESSHISTORYINFO.class, strWhere);
        List<ARCHIVE_ILLNESSHISTORYINFO> xinList = new ArrayList<ARCHIVE_ILLNESSHISTORYINFO>();
        // 手术:
        int surgeryId = surgeryRg.getCheckedRadioButtonId();
        // 外伤:
        int traumaId = traumaRg.getCheckedRadioButtonId();
        // 输血:
        int transfusureId = transfusureRg.getCheckedRadioButtonId();
        if (surgeryId != -1) {
            RadioButton surgeryRb = (RadioButton) view.findViewById(surgeryId);
            String type = surgeryRb.getText().toString().equals("有") ? "2" : "";
            ARCHIVE_ILLNESSHISTORYINFO illInfo1 = new ARCHIVE_ILLNESSHISTORYINFO();
            String reason1 = surgeryR1.getText().toString();
            String reason2 = surgeryR2.getText().toString();
            illInfo1.setILLNESSTYPE(type);
            illInfo1.setILLNESSNAME_OTHER(reason1);
            illInfo1.setIDCARD(NovaApplication.getUserInfo().getIDCARD());
            try {
                if (!TextUtils.isEmpty(timeEts[0].getText().toString())) {
                    Date date = format.parse(timeEts[0].getText().toString());
                    illInfo1.setDIAGNOSETIME(date);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }

            ARCHIVE_ILLNESSHISTORYINFO illInfo2 = new ARCHIVE_ILLNESSHISTORYINFO();
            illInfo2.setILLNESSTYPE(type);
            illInfo2.setILLNESSNAME_OTHER(reason2);
            illInfo2.setIDCARD(NovaApplication.getUserInfo().getIDCARD());
            try {
                if (!TextUtils.isEmpty(timeEts[1].getText().toString())) {
                    Date date = format.parse(timeEts[1].getText().toString());
                    illInfo2.setDIAGNOSETIME(date);
                }
            } catch (ParseException e) {

                e.printStackTrace();
            }
            xinList.add(illInfo1);
            xinList.add(illInfo2);

        }
        if (traumaId != -1) {
            RadioButton traumaRb = (RadioButton) view.findViewById(traumaId);
            String type = traumaRb.getText().toString().equals("有") ? "3" : "";
            ARCHIVE_ILLNESSHISTORYINFO illInfo1 = new ARCHIVE_ILLNESSHISTORYINFO();
            String reason1 = traumaR1.getText().toString();
            String reason2 = traumaR2.getText().toString();
            illInfo1.setILLNESSTYPE(type);
            illInfo1.setILLNESSNAME_OTHER(reason1);
            illInfo1.setIDCARD(NovaApplication.getUserInfo().getIDCARD());
            try {
                if (!TextUtils.isEmpty(timeEts[2].getText().toString())) {
                    Date date = format.parse(timeEts[2].getText().toString());
                    illInfo1.setDIAGNOSETIME(date);
                }
            } catch (ParseException e) {

                e.printStackTrace();
            }

            ARCHIVE_ILLNESSHISTORYINFO illInfo2 = new ARCHIVE_ILLNESSHISTORYINFO();
            illInfo2.setILLNESSTYPE(type);
            illInfo2.setILLNESSNAME_OTHER(reason2);
            illInfo2.setIDCARD(NovaApplication.getUserInfo().getIDCARD());
            try {
                if (!TextUtils.isEmpty(timeEts[3].getText().toString())) {
                    Date date = format.parse(timeEts[3].getText().toString());
                    illInfo2.setDIAGNOSETIME(date);
                }
            } catch (ParseException e) {

                e.printStackTrace();
            }
            xinList.add(illInfo1);
            xinList.add(illInfo2);
        }
        // 输血:
        if (transfusureId != -1) {
            RadioButton transfusureRb = (RadioButton) view.findViewById(transfusureId);
            String type = transfusureRb.getText().toString().equals("有") ? "4" : "";
            ARCHIVE_ILLNESSHISTORYINFO illInfo1 = new ARCHIVE_ILLNESSHISTORYINFO();
            String reason1 = transfusurnR1.getText().toString();
            String reason2 = transfusurnR2.getText().toString();
            illInfo1.setILLNESSTYPE(type);
            illInfo1.setILLNESSNAME_OTHER(reason1);
            illInfo1.setIDCARD(NovaApplication.getUserInfo().getIDCARD());
            try {
                if (!TextUtils.isEmpty(timeEts[4].getText().toString())) {
                    Date date = format.parse(timeEts[4].getText().toString());
                    illInfo1.setDIAGNOSETIME(date);
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }

            ARCHIVE_ILLNESSHISTORYINFO illInfo2 = new ARCHIVE_ILLNESSHISTORYINFO();
            illInfo2.setILLNESSTYPE(type);
            illInfo2.setILLNESSNAME_OTHER(reason2);
            illInfo2.setIDCARD(NovaApplication.getUserInfo().getIDCARD());
            try {
                if (!TextUtils.isEmpty(timeEts[5].getText().toString())) {
                    Date date = format.parse(timeEts[5].getText().toString());
                    illInfo2.setDIAGNOSETIME(date);
                }
            } catch (ParseException e) {

                e.printStackTrace();
            }
            xinList.add(illInfo1);
            xinList.add(illInfo2);

        }

        if (dieaseNo.isChecked()) {
            // 既往史疾病选中的是无
            clearGroup(null);
            // 无疾病
            ARCHIVE_ILLNESSHISTORYINFO illInfo = new ARCHIVE_ILLNESSHISTORYINFO();
            illInfo.setILLNESSNAME(getDiseasCode("无"));
            illInfo.setILLNESSTYPE("1");
            illInfo.setIDCARD(NovaApplication.getUserInfo().getIDCARD());
            xinList.add(illInfo);
        } else {
            // 既往史疾病
            String pops = "";
            for (int i = 0; i < diseaseEts.size(); i++) {
                String diease = diseaseEts.get(i).getText().toString();
                Log.e("diease", diease);
                Date illDate = null;
                try {
                    String date = timeEts[i + 6].getText().toString();
                    if (TextUtils.isEmpty(date)) {
                    } else {
                        illDate = format.parse(date);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (!TextUtils.isEmpty(diease)) {
                    ARCHIVE_ILLNESSHISTORYINFO illInfo = new ARCHIVE_ILLNESSHISTORYINFO();
                    illInfo.setILLNESSNAME(getDiseasCode(diease));
                    illInfo.setILLNESSTYPE("1");
                    illInfo.setIDCARD(NovaApplication.getUserInfo().getIDCARD());
                    illInfo.setDIAGNOSETIME(illDate);
                    setOtherIll(illInfo, diease);// 恶性肿瘤、其他、职业病
                    xinList.add(illInfo);

                    if ("高血压".equals(diease)) {
                        saveJBLX(PeopleType.GXY);
                    }
                    if ("糖尿病".equals(diease)) {
                        saveJBLX(PeopleType.TNB);
                    }
                    if ("冠心病".equals(diease)) {
                        saveJBLX(PeopleType.GXB);
                    }
                    if ("脑卒中".equals(diease)) {
                        saveJBLX(PeopleType.NCZ);
                    }
                    if ("严重精神障碍".equals(diease)) {
                        saveJBLX(PeopleType.JSB);
                    }
                    if ("结核病".equals(diease)) {
                        saveJBLX(PeopleType.FJH);
                    }

                }

            }
        }
        CheckBoxAdapter fAdapter = (CheckBoxAdapter) fatherGridView.getAdapter();
        CheckBoxAdapter mAdapter = (CheckBoxAdapter) motherGridView.getAdapter();
        CheckBoxAdapter bAdapter = (CheckBoxAdapter) brotherGridView.getAdapter();
        CheckBoxAdapter sAdapter = (CheckBoxAdapter) sonGridView.getAdapter();
        String fhis = fAdapter.getCheckedIdsStr();
        String mhis = mAdapter.getCheckedIdsStr();
        String bhis = bAdapter.getCheckedIdsStr();
        String shis = sAdapter.getCheckedIdsStr();

        ARCHIVE_FAMILYHISTORYINFO history = new ARCHIVE_FAMILYHISTORYINFO();// 家族史
        history.setFATHERHISTORY(fhis);
        history.setFATHERHISTORY_OTHER(fatherAdapter.getOther());
        history.setMOTHERHISTORY(mhis);
        history.setMOTHERHISTORY_OTHER(motherAdapter.getOther());
        history.setBROTHERSISTERHISTORY(bhis);
        history.setBROTHERSISTERHISTORY_OTHER(brotherAdapter.getOther());
        history.setCHILDRENHISTORY(shis);
        history.setCHILDRENHISTORY_OTHER(sonAdapter.getOther());
        history.setIDCARD(NovaApplication.getUserInfo().getIDCARD());
        if (!historys.contains(history)) {
            for (ARCHIVE_FAMILYHISTORYINFO info : historys) {
                fdbmanger.delete(info);
            }
            history.setNGUID(UUID.randomUUID().toString());
            fdbmanger.save(history);
        }
        BD_DD_INFO kitchenInfo = kitchenAdapter.getItemInDataset(kitchenSp.getSelectedIndex());
        BD_DD_INFO fuelInfo = fuelAdapter.getItemInDataset(fuelSp.getSelectedIndex());
        BD_DD_INFO waterInfo = waterAdapter.getItemInDataset(waterSp.getSelectedIndex());
        BD_DD_INFO wcInfo = wcAdaper.getItemInDataset(wcSp.getSelectedIndex());
        BD_DD_INFO animalInfo = animalAdapter.getItemInDataset(animalSp.getSelectedIndex());

        ARCHIVE_ENVIRONMENT environment = new ARCHIVE_ENVIRONMENT();// 生活环境
        environment.setBLOWMEASURE(kitchenInfo.getID());// 厨房排风设施1:无 2:油烟机 3:换气扇
        // 4:烟囱
        environment.setFUELTYPE(fuelInfo.getID());// 燃料类型1:液化气 2:煤 3:天然气 4:沼气
        // 5:柴火 6 其他
        environment.setDRINKWATER(waterInfo.getID());// 饮水1:自来水 2:经净化过滤的水 3:井水
        // 4:河湖水 5:塘水 6:其他
        environment.setTOILET(wcInfo.getID());// 厕所1:卫生厕所 2:一格或二格粪池式 3:马桶 4:露天粪坑
        // 5:简易棚厕
        environment.setLIVESTOCKRAIL(animalInfo.getID());// 禽畜栏1:单设 2:室内 3:室外
        // 4:其他
        environment.setIDCARD(NovaApplication.getUserInfo().getIDCARD());

        if (environmentList != null && environmentList.size() > 0) {
            for (ARCHIVE_ENVIRONMENT env : environmentList) {
                fdbmanger.delete(env);
            }
        }
        saveOrDelete(xinList, oldList);
        fdbmanger.save(environment);

        Toast.makeText(getActivity(), "保存成功", 0).show();

    }

    private String getDiseasCode(String diseasName) {
        for (BD_DD_INFO info : diseasInfos_jb) {
            if (info.getDATAINFO().equals(diseasName)) {
                Log.e(TAG, info.toString());
                return info.getID();
            }
        }
        return null;
    }

    /**
     * 遍历疾病列表【显示疾病名称】
     */
    private String getDiseasName(String diseasCode) {
        String name = "";
        for (BD_DD_INFO info : diseasInfos_jb) {
            if (info.getID().equals(diseasCode)) {
                name = info.getDATAINFO();
            }
        }

        return name;
    }

    /**
     * 获取 恶性肿瘤、职业病、其他
     *
     * @return
     * @author 王婷婷
     * @date 2017年9月11日 下午8:05:35
     */
    private List<String> getEtDiseasName() {
        List<String> list = new ArrayList<String>();
        for (EditText et : diseaseEts) {
            String text = et.getText().toString();
            int first = text.indexOf("(");
            int last = text.lastIndexOf(")");
            if (!(first == -1 || last == -1)) {
                text = text.substring(0, first);
            }
            list.add(text);

        }
        return list;

    }

    /**
     * 获取疾病 顺序
     */
    private int getCheckIndex(String diseaseCode) {
        for (int i = 0; i < diseasInfos_jb.size(); i++) {
            if (diseaseCode.equals(diseasInfos_jb.get(i).getID())) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.healthy_father_btn) {
            setRadioVisible(fatherGridView);
        } else if (id == R.id.healthy_mother_btn) {
            setRadioVisible(motherGridView);
        } else if (id == R.id.healthy_brother_btn) {
            setRadioVisible(brotherGridView);
        } else if (id == R.id.healthy_son_btn) {
            setRadioVisible(sonGridView);
        } else {
        }
    }

    private void setRadioVisible(MyGridView gridView) {
        if (fatherGridView.getVisibility() == View.VISIBLE) {
            fatherGridView.setVisibility(View.GONE);
        }
        if (motherGridView.getVisibility() == View.VISIBLE) {
            motherGridView.setVisibility(View.GONE);
        }
        if (brotherGridView.getVisibility() == View.VISIBLE) {
            brotherGridView.setVisibility(View.GONE);
        }
        if (sonGridView.getVisibility() == View.VISIBLE) {
            sonGridView.setVisibility(View.GONE);
        }

        gridView.setVisibility(View.VISIBLE);
    }

    private String notNull(String str) {
        if (TextUtils.isEmpty(str)) {
            return "";
        }
        return str;
    }

    private String notNull(int str) {
        if (str == 0) {
            return "0";
        }
        return String.valueOf(str);
    }

    private Date notNull(Date date) {
        if (date == null) {
            return new Date();
        }
        return date;
    }

    @Override
    public void setTizhong(String value) {

    }

    @Override
    public void setXuetang(String value) {

    }

    @Override
    public void setXueya(String gaoya, String diya, String mailv) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (surgeryRg.getCheckedRadioButtonId() != R.id.healthy_surgeryyes_rb) {
            surgeryR1.setText("");
            surgeryR2.setText("");
            surgeryR1.setEnabled(false);
            surgeryR2.setEnabled(false);
            rTimeEt1.setDatePickerEnabled(false);
            rTimeEt2.setDatePickerEnabled(false);
        } else {
            surgeryR1.setEnabled(true);
            surgeryR2.setEnabled(true);
            rTimeEt1.setDatePickerEnabled(true);
            rTimeEt2.setDatePickerEnabled(true);
        }
        if (traumaRg.getCheckedRadioButtonId() != R.id.healthy_traumayes_rb) {
            traumaR1.setText("");
            traumaR2.setText("");
            traumaR1.setEnabled(false);
            traumaR2.setEnabled(false);
            rTimeEt3.setDatePickerEnabled(false);
            rTimeEt4.setDatePickerEnabled(false);
        } else {
            traumaR1.setEnabled(true);
            traumaR2.setEnabled(true);
            rTimeEt3.setDatePickerEnabled(true);
            rTimeEt4.setDatePickerEnabled(true);
        }
        if (transfusureRg.getCheckedRadioButtonId() != R.id.healthy_transfusurnyes_rb) {
            transfusurnR1.setText("");
            transfusurnR2.setText("");
            transfusurnR1.setEnabled(false);
            transfusurnR2.setEnabled(false);
            rTimeEt5.setDatePickerEnabled(false);
            rTimeEt6.setDatePickerEnabled(false);
        } else {
            transfusurnR1.setEnabled(true);
            transfusurnR2.setEnabled(true);
            rTimeEt5.setDatePickerEnabled(true);
            rTimeEt6.setDatePickerEnabled(true);
        }

    }

    /**
     * 获取人群分类
     *
     * @author 王婷婷
     * @date 2017年9月22日 上午11:53:50
     */
    public void getGroup() {
        userInfo = NovaApplication.getUserInfo();
        List<String> popList = new ArrayList<String>();
        if (!TextUtils.isEmpty(userInfo.getPOPULATION_TYPE())) {
            String popStr = userInfo.getPOPULATION_TYPE();
            String[] pops = popStr.split(",");
            popList = Arrays.asList(pops);
            // isChild = popList.contains("2");
            // isPregnant = popList.contains("3");
            // isOlder = popList.contains("4");
            isPsychosis = popList.contains("5");
            isHypertension = popList.contains("6");
            isDiabetes = popList.contains("7");
            isCHD = popList.contains("8");
            isStroke = popList.contains("9");
            // isHandicapped = popList.contains("10");
            isTB = popList.contains("11");
            Log.e(TAG, "getGroup() " + userInfo.getPOPULATION_TYPE());
        }

    }

    /**
     * 清空疾病人群分类
     *
     * @author 王婷婷
     * @date 2017年9月22日 上午11:54:07
     */
    private void clearGroup(String type) {
        JBRQData.clearGroup(type, userInfo);

        PersonalFileActivity activity = (PersonalFileActivity) getActivity();
        activity.freshDetailInfoData();
    }

    /**
     * 保存疾病
     *
     * @author 王婷婷
     * @date 2017年9月22日 下午3:05:53
     */
    private void saveJBLX(String peopleType) {
        JBRQData.saveJBLX(peopleType, userInfo);

        PersonalFileActivity activity = (PersonalFileActivity) getActivity();
        activity.freshDetailInfoData();
    }

    // public void getGroup() {
    //
    // List<HD_PERSONAL_JKTZ> jktzs =
    // fdbmanger.findAllByWhere(HD_PERSONAL_JKTZ.class,
    // "idCard='" + userInfo.getIDCARD() + "'");
    // if (jktzs.size() > 0) {
    // HD_PERSONAL_JKTZ jktz = jktzs.get(0);
    //
    //// 2：儿童，3：孕产妇，4：老年人，5：重精神病，6：高血压，7：糖尿病，8：冠心病，9：脑卒中
    //// isChild = ISTAG.equals(jktz.getIset());
    //// isPregnant = ISTAG.equals(jktz.getIsycf());
    //// isOlder = ISTAG.equals(jktz.getIslnr());
    // isPsychosis = ISTAG.equals(jktz.getIsjsb());
    // isHypertension = ISTAG.equals(jktz.getIsgxy());
    // isDiabetes = ISTAG.equals(jktz.getIstnb());
    // isCHD = ISTAG.equals(jktz.getIsgxb());
    // isStroke = ISTAG.equals(jktz.getIsncz());
    //// isHandicapped = ISTAG.equals(jktz.getIscjr());
    // isTB = ISTAG.equals(jktz.getIstb());
    // }

    // }

    private void setOtherIll(ARCHIVE_ILLNESSHISTORYINFO illInfo, String text) {
        int first = text.indexOf("(");
        int last = text.lastIndexOf(")");
        if (first == -1 || last == -1) {
            return;
        }
        String detail = text.substring(first + 1, last);
        if (text.startsWith("恶性肿瘤")) {
            illInfo.setILLNESSNAME("DM99-01_6");
            illInfo.setTHERIOMA(detail);
            illInfo.setILLNESSTYPE("1");
        } else if (text.startsWith("职业病")) {
            illInfo.setILLNESSNAME("DM99-01_12");
            illInfo.setJOBILLNESS(detail);
            illInfo.setILLNESSTYPE("1");
        } else if (text.startsWith("其他")) {
            illInfo.setILLNESSNAME("DM99-01_99");
            illInfo.setILLNESS_OTHER(detail);
            illInfo.setILLNESSTYPE("1");
        }
    }

    private ARCHIVE_ILLNESSHISTORYINFO getInfo(List<ARCHIVE_ILLNESSHISTORYINFO> list, String code) {
        if (list == null && code == null) {
            return null;
        }
        for (ARCHIVE_ILLNESSHISTORYINFO info : list) {
            if (code.equals(info.getILLNESSNAME())) {
                return info;
            }

        }
        return null;
    }

    @Override
    public void setTiWen(String tiwen) {

    }

    @Override
    public void setXueHongDanBai(String xhdb) {

    }

    @Override
    public void setMaiLv(String mailv) {

    }

    @Override
    public void setLiBangECG(String libangEcgResult, String time) {

    }

    @Override
    public void setNiaoYeFenxi(String niaoDanYuan, String qianXue, String DanHongSu, String tongti, String puTaoTang,
                               String danBaiZhi, String PH, String yaXiaoSuan, String baiXiBao, String biZhong, String weiShengSu) {

    }

    @Override
    public void setXinLv(String xinlv) {

    }

    /**
     * 设置选中个数
     *
     * @return
     * @author 王婷婷
     * @date 2017年6月22日 下午2:17:06
     */
    private boolean setCheckMax() {
        int count = 0;
        int length = diseaseCbs.size();
        for (int i = 0; i < length; i++) {
            if (diseaseCbs.get(i).isChecked()) {
                count++;
            }
            if (count > 5) {
                return false;
            }
        }
        return true;

    }

    @Override
    public void onResume() {
        super.onResume();
        getGroup();
        dieaseNo.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    for (int i = 1; i < diseaseCbs.size(); i++) {
                        diseaseCbs.get(i).setChecked(false);
                        diseaseCbs.get(i).setEnabled(false);
                    }
                    // gaoxueyaCb.setEnabled(false);
                    // tangniaobingCb.setEnabled(false);
                    // guanxinbingCb.setEnabled(false);
                    // feibingCb.setEnabled(false);

                } else {
                    for (int i = 1; i < diseaseCbs.size(); i++) {
                        diseaseCbs.get(i).setEnabled(true);
                    }
                }

            }
        });
    }

}
